package com.ssii.www.myproject.service.impl;

import com.ssii.www.myproject.common.util.BCryptUtils;
import com.ssii.www.myproject.domain.Role;
import com.ssii.www.myproject.domain.User;
import com.ssii.www.myproject.repository.PermissionRepository;
import com.ssii.www.myproject.repository.UserRepository;
import com.ssii.www.myproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
//@Transactional
public class UserServiceImpl extends BaseServiceImpl<User, Long> implements UserService {
  @Autowired
  private UserRepository userRepository;

  @Override
  //新增
  public void save(User user) {
    System.out.println(user.getId() + "  " + user.getRoles().size());
    if (user.getId() == null) {
      user.setForbidden(0L);
      Role role = new Role();
      role.setId(2L);
      List<Role> list = new ArrayList<>();
      list.add(role);
      user.setRoles(list);
      user.setPassword(BCryptUtils.hashpw(user.getPassword(), BCryptUtils.gensalt()));
    }
    //有id的才比较
    if (user.getId() != null) {
      //传过来的密码
      String password = user.getPassword();
      //数据库查询到的密码
      String hashed = userRepository.findOne(user.getId()).getPassword();
      //如果传过来的密码不匹配数据库的 则更改密码 String覆写了equals方法
      if (!password.equals(hashed)) {
        user.setPassword(BCryptUtils.hashpw(password, BCryptUtils.gensalt()));
//    String encrypt = MD5Utils.encrypt(user.getPassword());
//    user.setPassword(encrypt);
      }
    }
    userRepository.save(user);
  }

  /**
   * 根据id改变状态
   *
   * @param id
   */
  @Override
  public void change(Long id) {
    User user = userRepository.findOne(id);
//    if (user.getForbidden()==1L){
//      user.setForbidden(0L);
//      userRepository.save(user);
//      return;
//    }
//    if(user.getForbidden()==0L){
//      user.setForbidden(1L);
//      userRepository.save(user);
//      return;
//    }
    Long forbidden = user.getForbidden();
    user.setForbidden(forbidden == 1L ? 0L : 1L);
    userRepository.save(user);

  }

  /**
   * 重置密码方法
   *
   * @param id
   * @param password
   */
  @Override
  public void reset(Long id, String password) {
    User one = findOne(id);
    String hashed = BCryptUtils.hashpw(password, BCryptUtils.gensalt());
    one.setPassword(hashed);
//    String encrypt = MD5Utils.encrypt(password);
//    one.setPassword(encrypt);
    super.save(one);
  }

  @Override
  @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
  public User getUserByName(String name) {
    return userRepository.getUserByName(name);
  }


}
